package cn.touna.jss.modules.custom.batch;

import com.alibaba.fastjson.JSONObject;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.IOException;
import java.io.StringWriter;

public class RequestParamProcessor implements ItemProcessor {

    private String formatStr;
    private Template template;

    public String getFormatStr() {
        return formatStr;
    }

    public void setFormatStr(String formatStr) throws IOException {
        this.formatStr = formatStr;
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
        StringTemplateLoader loader = new StringTemplateLoader();

        String DEFAULT = "default";
        loader.putTemplate(DEFAULT,formatStr);
        cfg.setTemplateLoader(loader);
        template = cfg.getTemplate(DEFAULT);
    }

    @Override
    public JSONObject process(JSONObject item) {
        StringWriter stringWriter = new StringWriter();
        try {
            template.process(item,stringWriter);
            item.put(BatchConstant.COLUMN_REQUEST,stringWriter.toString());
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }
}
